using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using StudentManagement.Application.DTOs;
using StudentManagement.Application.Services;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace StudentManagement.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CourseController : ControllerBase
    {
        private readonly ICourseService _courseService;

        public CourseController(ICourseService courseService)
        {
            _courseService = courseService;
        }

        // GET: api/Course
        [HttpGet]
        [Authorize]
        public async Task<ActionResult<IEnumerable<CourseDTO>>> GetAllCourses()
        {
            var courses = await _courseService.GetAllCoursesAsync();
            return Ok(courses);
        }

        // GET: api/Course/{id}
        [HttpGet("{id}")]
        [Authorize]
        public async Task<ActionResult<CourseDTO>> GetCourseById(int id)
        {
            var course = await _courseService.GetCourseByIdAsync(id);
            if (course == null)
            {
                return NotFound();
            }
            return Ok(course);
        }

        // GET: api/Course/by-code/{courseCode}
        [HttpGet("by-code/{courseCode}")]
        [Authorize]
        public async Task<ActionResult<CourseDTO>> GetCourseByCode(string courseCode)
        {
            var course = await _courseService.GetCourseByCodeAsync(courseCode);
            if (course == null)
            {
                return NotFound();
            }
            return Ok(course);
        }

        // GET: api/Course/by-teacher/{teacherId}
        [HttpGet("by-teacher/{teacherId}")]
        [Authorize]
        public async Task<ActionResult<IEnumerable<CourseDTO>>> GetCoursesByTeacherId(int teacherId)
        {
            var courses = await _courseService.GetCoursesByTeacherIdAsync(teacherId);
            return Ok(courses);
        }

        // GET: api/Course/search/{keyword}
        [HttpGet("search/{keyword}")]
        [Authorize]
        public async Task<ActionResult<IEnumerable<CourseDTO>>> SearchCourses(string keyword)
        {
            var courses = await _courseService.SearchCoursesAsync(keyword);
            return Ok(courses);
        }

        // POST: api/Course
        [HttpPost]
        [Authorize(Roles = "Admin,Teacher")]
        public async Task<ActionResult<CourseDTO>> CreateCourse([FromBody] CourseDTO courseDTO)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var createdCourse = await _courseService.CreateCourseAsync(courseDTO);
                return CreatedAtAction(nameof(GetCourseById), new { id = createdCourse.Id }, createdCourse);
            }
            catch (System.Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // PUT: api/Course/{id}
        [HttpPut("{id}")]
        [Authorize(Roles = "Admin,Teacher")]
        public async Task<ActionResult<CourseDTO>> UpdateCourse(int id, [FromBody] CourseDTO courseDTO)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var updatedCourse = await _courseService.UpdateCourseAsync(id, courseDTO);
                if (updatedCourse == null)
                {
                    return NotFound();
                }
                return Ok(updatedCourse);
            }
            catch (System.Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // DELETE: api/Course/{id}
        [HttpDelete("{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> DeleteCourse(int id)
        {
            try
            {
                await _courseService.DeleteCourseAsync(id);
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("课程不存在"))
                {
                    return NotFound();
                }
                return BadRequest(ex.Message);
            }
        }

        // GET: api/Course/course-code-exists/{courseCode}
        [HttpGet("course-code-exists/{courseCode}")]
        [Authorize(Roles = "Admin,Teacher")]
        public async Task<ActionResult<bool>> CourseCodeExists(string courseCode)
        {
            var exists = await _courseService.CourseCodeExistsAsync(courseCode);
            return Ok(exists);
        }
    }
}